import { PlusOutlined } from '@ant-design/icons';
import { Image, Upload, message } from 'antd';
import React, { useEffect, useState } from 'react';

import type { GetProp, UploadFile, UploadProps } from 'antd';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const getBase64 = (file: FileType): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

// 允许上传的文件类型
const ALLOWED_FILE_TYPES = ['image/jpeg', 'image/png'];
// 最大文件大小 3MB
const MAX_FILE_SIZE = 3 * 1024 * 1024;

export default function UploadPicture({
  portraitList = [],
  maxCount = 1,
  onUploadSuccess,
  disabled = false,
  title = '上传图片',
}: {
  portraitList?: string[]; // 改为直接接收完整URL数组
  maxCount?: number;
  onUploadSuccess?: (fileUrlList: string[]) => void; // 改为返回完整URL数组
  disabled?: boolean;
  title?: string;
}) {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewIndex, setPreviewIndex] = useState(0);

  // 上传前校验文件类型和大小
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    const isAllowedType = ALLOWED_FILE_TYPES.includes(file.type);
    if (!isAllowedType) {
      message.error('只能上传 JPG/PNG 格式的图片!');
      return Upload.LIST_IGNORE;
    }

    const isLtSize = file.size <= MAX_FILE_SIZE;
    if (!isLtSize) {
      message.error('图片大小不能超过 3MB!');
      return Upload.LIST_IGNORE;
    }

    return true;
  };

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }
    const currentIndex = fileList.findIndex((item) => item.uid === file.uid);
    setPreviewIndex(currentIndex);
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  useEffect(() => {
    if (portraitList.length > 0) {
      console.log(portraitList);
      setFileList(
        portraitList.map((url, index) => ({
          uid: `preview-${index}`,
          name: `image-${index}.png`,
          status: 'done',
          url, // 直接使用完整URL
          response: { success: url }, // 假设后端返回的是完整URL
        })),
      );
    }
  }, [portraitList]);

  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList);

    // 提取所有已上传的完整URL
    const uploadedUrls = newFileList
      .map((file) => file.response?.success)
      .filter(Boolean) as string[];
    console.log(uploadedUrls);

    onUploadSuccess?.(uploadedUrls);
  };

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>{title}</div>
    </button>
  );

  return (
    <>
      <Upload
        disabled={disabled}
        action="/api/file/oss/upload" // 确保后端直接返回完整URL
        listType="picture-card"
        fileList={fileList}
        onPreview={handlePreview}
        onChange={handleChange}
        beforeUpload={beforeUpload}
        maxCount={maxCount}
        data={{ group: 'T68' }}
      >
        {fileList.length >= maxCount ? null : uploadButton}
      </Upload>

      <Image.PreviewGroup
        preview={{
          visible: previewOpen,
          current: previewIndex,
          onChange: (current) => setPreviewIndex(current),
          onVisibleChange: (visible) => setPreviewOpen(visible),
          afterOpenChange: (visible) => !visible && setPreviewImage(''),
        }}
        items={fileList.map((file) => file.url || file.preview || '')} // 直接使用文件URL
      />
    </>
  );
}
